package com.open.capacity.finance.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.util.XsteamUtil;
import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.finance.dao.*;
import com.open.capacity.finance.dto.SourceExcelDto;
import com.open.capacity.finance.dto.SourcePzErrorDto;
import com.open.capacity.finance.entity.*;
import com.open.capacity.finance.service.SourcePzService;
import com.open.capacity.finance.service.SourcePzUnionService;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.finance.util.POIExcelUtil;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.user.service.SysCompanyService;
import com.open.capacity.utils.StringUtil;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SourcePzUnionServiceImpl implements SourcePzUnionService {

    @Autowired
    private SysCompanyService companyService;

    @Autowired
    private SourcePzUnionDao sourcePzDao;


    /**
     * 添加
     */
    @Transactional
    public synchronized int save2db(String companyId, Integer kjnd, Integer importway, String url) {
        MultipartFile multipartFile = FileUtil.toMultipartFile("unionxszXls", url);

        try {
            SourceExcelDto result = validition(multipartFile, kjnd);

            SysCompany company = companyService.findById(companyId);
            //删除旧数据
            if (importway == 1) {
                delete(companyId, kjnd);
            }

            SourcePz pz = null;
            for (SourceImport item : result.getList()) {
                pz = new SourcePz();

                pz.setCompanyId(companyId);
                pz.setCompanyName(company.getFullName());
                pz.setKjnd(kjnd);
                pz.setKjqj(Integer.parseInt(item.getPzrq().substring(5, 7)));
                pz.setPzrq(item.getPzrq());
                pz.setPzh(item.getPzh());
                pz.setPzlx(item.getPzh().split("-")[0]);
                pz.setZy(item.getZy());
                pz.setKjkmCode(item.getKjkm().split(" ")[0]);
                pz.setKjkmName(item.getKjkm().split(" ")[1]);
                pz.setJ(item.getJ());
                pz.setD(item.getD());

                sourcePzDao.save(pz);
            }

        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

        return 1;
    }

    /**
     * 校验excel数据
     */
    private SourceExcelDto validition(MultipartFile multipartFile, Integer kjnd) throws IOException {
        StringBuilder errMsg = new StringBuilder();
        InputStream inputStream = multipartFile.getInputStream();
        Workbook wb = WorkbookFactory.create(inputStream);

        Sheet sheet = wb.getSheetAt(0);
        // 获取最大行数(或者sheet.getLastRowNum())
        int rownum = sheet.getPhysicalNumberOfRows();

        Row header;
        Row row;
        Row row1 = sheet.getRow(1);
        Row row2 = sheet.getRow(2);
        Row row3 = sheet.getRow(3);
        Row row4 = sheet.getRow(4);
        Row row5 = sheet.getRow(5);

        //判断数据从第几行开始，表头有可能多一行
        int startRowIndex = 4;
        int headerRowIndex = 3;
        if ("日期".equals(row3.getCell(0).getStringCellValue())) {
            startRowIndex = 4;
            headerRowIndex = 3;
        } else if ("日期".equals(row4.getCell(0).getStringCellValue())) {
            startRowIndex = 5;
            headerRowIndex = 4;
        } else if ("日期".equals(row5.getCell(0).getStringCellValue())) {
            startRowIndex = 6;
            headerRowIndex = 5;
        }

        String zt = "";
        String titleperiod = "";
        String company = row1.getCell(0).getStringCellValue();
        if (company.contains("账套")) {
            zt = row1.getCell(0).getStringCellValue();
            titleperiod = row2.getCell(0).getStringCellValue();
        } else {
            zt = row2.getCell(0).getStringCellValue();
            titleperiod = row3.getCell(0).getStringCellValue();
        }
        String companyName = company;
        String ztName = zt;
        companyName = company.replace("单位：", "");
        ztName = ztName.replace("账套：", "");

        SourceExcelDto result = new SourceExcelDto();
        result.setCompanyName(companyName);
        result.setZtName(ztName);
        result.setKjnd(kjnd.toString());
        result.setPeriod(titleperiod);
        List<SourceImport> list = new ArrayList<>();
        SourceImport item;

        header = sheet.getRow(headerRowIndex);

        // 处理行数据
        for (int i = startRowIndex; i < rownum; i++) {
            row = sheet.getRow(i);
            // 遇到空行则结束
            if (row == null) {
                break;
            }

            String pzrq = POIExcelUtil.getString(row.getCell(0));//日期

            if (StringUtil.isEmpty(pzrq)) {
                continue;
            }

            String pzh = POIExcelUtil.getString(row.getCell(1));//凭证号
            String zy = POIExcelUtil.getString(row.getCell(2));//摘要
//
            BigDecimal j = POIExcelUtil.getNumber(row.getCell(3));//借方金额
            BigDecimal d = POIExcelUtil.getNumber(row.getCell(4));//贷放金额
            String pjlx = POIExcelUtil.getString(row.getCell(5));//票据类型
            String pjh = POIExcelUtil.getString(row.getCell(6));//票据号
            String kjkm = POIExcelUtil.getString(row.getCell(7));//会计科目
            String dfkm = POIExcelUtil.getString(row.getCell(8));//对方科目


            item = new SourceImport();
            item.setPzrq(pzrq);
            item.setPzh(pzh);
            item.setZy(zy);
            item.setJ(j);
            item.setD(d);
            item.setPjlx(pjlx);
            item.setPjh(pjh);
            item.setKjkm(kjkm);
            item.setDfkm(dfkm);

            list.add(item);
        }
        result.setList(list);

        result.setNomalCount(list.size());
        result.setErrorCount(0);
        result.setErrorMsg(errMsg.toString());
        return result;
    }


    /**
     * 删除
     *
     * @param companyId
     */
    @Transactional
    public int delete(String companyId, Integer kjnd) {
        sourcePzDao.deleteByCompanyIdAndKjnd(companyId, kjnd);
        return 1;
    }


    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public SourcePz findById(String id) {
        return sourcePzDao.findById(id);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<SourcePz> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<SourcePz> list = sourcePzDao.findAll(params);
        PageInfo<SourcePz> pageInfo = new PageInfo(list);

        return PageResult.<SourcePz>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SourcePz> findAll(Map<String, Object> params) {
        return sourcePzDao.findAll(params);
    }
}
